<template>
	<view>
        <uv-loading-page :loading="isLoadding" loadingText="座位图加载中..." loading-mode="circle"></uv-loading-page>
        <template v-if="!isLoadding">
            <view class="seatNotice">
                <view class="seatItem">
                    <image
                        src="https://wx.sijiyoufu.com/static/imgs/sites/seat_sold.svg"
                        mode="widthFix" style="width:18px;"
                    />
                    <text>已售</text>
                </view>
                <view class="seatItem" v-for="(item , index) in areaPrice" :key="index">
                    <image
                        :src="item.area?areaMapp[item.area].icon:areaMapp.icon"
                        mode="widthFix" style="width:18px;"
                    />
                    <text>￥{{ item.price }}</text>
                </view>
                <view class="seatItem">
                    <image
                        src="https://wx.sijiyoufu.com/static/imgs/sites/seat_couple.svg"
                        mode="widthFix" style="width:43px;"
                    />
                    <text>情侣座</text>
                </view>
            </view>
            <movable-area id="movable" scale-area class="online_body" width="100%" v-if="Base.maxrow > 0">
                <movable-view 
                    direction="all"  
                    :x="-(Base.maxcolumn * Config.width + Config.width * 2 - sysWidth)" y="0" 
                    :style="`width:${Base.maxcolumn * Config.width + Base.maxcolumn  * Config.gap + Config.width * 2}px;height:${Base.maxrow * Config.height + Base.maxrow  * Config.gap + Config.height * 2}px`" 
                    scale
                    inertia
                    damping="100"
                    :scale-min="Config.minZoom" 
                    :scale-max="Config.maxZoom"
                    @change="changeView"
                    @scale="scaleView"
                    animation>
                    <view class="screen_body">
                        {{ Opi.roomname }} {{ Opi.roomid }}
                    </view>
                    <view class="online_body_number" :style="`transform: translateX(${-viewX / Config.scale}px);top:${Config.screen}px`">
                        <view class="index_number" :style="`width:${Config.width}px;height:${Config.height}px;line-height:${Config.height}px;margin-bottom:${Config.gap}px`" v-for="(num,index) in Base.maxrow" :key="index">{{SeatIndex[num]?SeatIndex[num].rowname:''}}</view>
                    </view>
                    <template v-for="(seat , index) in Seats" :key="index">
                        <view class="cell_base_box" :style="`
                            width:${seat.flag == 1?Config.leftWidth:(seat.flag == 2?Config.rightWidth:Config.width)}px;
                            height:${Config.height}px;
                            left:${seat.column * Config.width + seat.column * Config.gap - (seat.flag == 2?Config.gap - 2:0)}px;
                            top:${(seat.row - 1) * Config.height + (seat.row - 1) * Config.gap + Config.screen}px;
                            background-image:url(${
                                seat.flag == 0?(
                                    seat.status == 0?seatMap.locked:(checkedMap[seat.seatid]?seatMap.checked:(seat.area?areaMapp[seat.area].icon:areaMapp.icon))
                                ):(
                                    seat.status == 0?
                                    (seat.flag == 1?seatMap.leftLocked:seatMap.rightLocked):
                                    (checkedMap[seat.seatid]?(seat.flag == 1?seatMap.leftChecked:seatMap.rightChecked):(
                                        seat.flag == 1?(seat.area?areaMapp[seat.area].leftIcon:areaMapp.leftIcon):(seat.area?areaMapp[seat.area].rightIcon:areaMapp.rightIcon)
                                    ))
                                )
                            })
                            `"
                            @click='triggerSeat(seat)'
                            ></view>
                    </template>
                </movable-view>
            </movable-area>
            <view class="opi_info" v-if="Opi.moviename">
                <view class="title">{{ Opi.moviename }}</view>
                {{ formatDateToTime(Opi.playtime,5,10) }} {{ formatDateToTime(Opi.playtime,11, 16) }} - {{ formatDateToTime(Opi.closetime,11, 16) }} {{ Opi.roomid }}

                <view class="selector">
                    <template v-if="showCheckedMap.length > 0">
                        <view v-for="(item , index) in showCheckedMap" :key="index" class="selector_item" @click='triggerSeat(item.value[0])'>
                            ￥{{ areaMapp[item.value[0].area]?(item.value[1]?(areaMapp[item.value[0].area].price * 1 + areaMapp[item.value[1].area].price * 1):areaMapp[item.value[0].area].price):areaMapp.price }}
                            <text>{{ item.value[0].name }} {{ item.value[1]?' | ' + item.value[1].name :'' }}</text>
                            <uv-icon size="13" name="close" class="image"></uv-icon>
                        </view>
                    </template>
                    <view v-else class="selector_item">
                        <text class="notice">请选择座位</text>
                    </view>
                </view>
            </view>
            <view class="btn bg-line-color" @click="CheckSeatPosition">确认选座</view>
        </template>
    </view>
</template>

<script setup lang="ts">
const app = getApp()
import { ref , getCurrentInstance,computed} from 'vue'
import { onLoad , onShow} from "@dcloudio/uni-app"
import { getSeats , createMovieOrder , validSeatPosition , getOpiDetail} from "@/api/movie"
import { useUCenterStore } from '@/stores/uCenter'
const isLoadding = ref<any>(true)
const Base = ref<any>({}) //座位基座信息
const Seats = ref<any>([]) //座位图信息
const Opi = ref<any>({}) //场次价格信息
const store = useUCenterStore()
const member = computed(() => {
  return store.memberInfo
})
const checkLogin = () => {
  if(!member.value.mobile){
    //存储当前路由地址，授权完毕回调
    uni.hideLoading()
    store.$patch((state) => {
        state.redirectPath = '/pages/movie/resolveSeats'
    })
    uni.navigateTo({
      url: '/pages/auth/index'
    })
    return false
  }else return true
}
const Config = ref<any>({
    width:23,
    leftWidth:28,
    rightWidth:28,
    height:23,
    maxZoom:1.5,
    minZoom:0.5,
    gap:6,
    scale:1,
    screen:52
})

const viewX = ref<any>(0)
const viewY = ref<any>(0)
const changeView = (e : any) => {
    const {x,y} = e.detail
    viewX.value = x;
    viewY.value = y
}
const scaleView = (e : any) => {
    const {x,y,scale} = e.detail
    viewX.value = x;
    viewY.value = y
    Config.value.scale = scale
}
const SeatIndex = ref<any>({})
const areaPrice = ref<any>([])
const areaMapp = ref<any>({})
const seatMap = ref<any>({
    locked:'https://wx.sijiyoufu.com/static/imgs/sites/seat_sold.svg',
    leftLocked:'https://wx.sijiyoufu.com/static/imgs/sites/seat_couple_sold_left.svg',
    rightLocked:'https://wx.sijiyoufu.com/static/imgs/sites/seat_couple_sold_right.svg',
    checked:'https://wx.sijiyoufu.com/static/imgs/sites/seat_selected2.svg',
    leftChecked:'https://wx.sijiyoufu.com/static/imgs/sites/seat_couple_selected_left.svg',
    rightChecked:'https://wx.sijiyoufu.com/static/imgs/sites/seat_couple_selected_right.svg',
})
const checkedMap = ref<any>({})
const showCheckedMap = ref<any>([])
const triggerSeat = (res : any) => {
    if(res.status != 0){
        
        const number = res.lovegroup ? res.lovegroup.substring(0, res.lovegroup.length - 1) : ""
        const position = res.lovegroup ? res.lovegroup.substring(res.lovegroup.length - 1) : ""
        const oppsite = position == "R" ? "L" : position == "L" ? "R" : ""
        const target = number + oppsite
        
        let loveSeat = ''
        if(res.flag != 0){
            for(var i in Seats.value){
                if(Seats.value[i].lovegroup == target){
                    loveSeat = Seats.value[i]
                    break
                }
            }
        }
        if(checkedMap.value[res.seatid]){
            delete checkedMap.value[res.seatid]
            removeShowSeat(res)
            if(loveSeat && checkedMap.value[loveSeat.seatid])delete checkedMap.value[loveSeat.seatid]
        }else{
            const count = Object.keys(checkedMap.value).length + (loveSeat?2:1)
            if(count > Base.value.maxcanbuy){
                uni.showToast({icon:'none','title':`最多可选择${Base.value.maxcanbuy}个座位`})
                return
            }
            
            checkedMap.value[res.seatid] = res;
            if(loveSeat){
                checkedMap.value[loveSeat.seatid] = loveSeat;
                showCheckedMap.value.push({
                    key:[res.seatid,loveSeat.seatid],
                    value:[res,loveSeat]
                })
            }else{
                showCheckedMap.value.push({
                    key:[res.seatid],
                    value:[res]
                })
            }
        }
    }
}

const removeShowSeat = (res : any) => {
    showCheckedMap.value = showCheckedMap.value.filter(item => {
        return !item.key.includes(res.seatid)
    })
}

const formatDateToTime = (str : any,start : any, end : any) => {
    return str.slice(start, end)
}

const CheckSeatPosition = () => {
    uni.showLoading({title:'锁定座位中...'})
    let validateArr = [],
        validateTxt = ""
    for (let i of Object.values(checkedMap.value)) {
        let tempArr = [];
        for (let j of Seats.value) {
            if (i.rowname == j.rowname) {
                tempArr.push(j);
            }
        }
        for (let k = 0; k < tempArr.length; k++) {
            for (let l = k + 1; l < tempArr.length; l++) {
                if (tempArr[k].column > tempArr[l].column) {
                    let temp = {};
                    temp = tempArr[k];
                    tempArr[k] = tempArr[l];
                    tempArr[l] = temp;
                }
            }
        }
        if (validateArr.indexOf(JSON.stringify(tempArr)) < 0) {
            validateArr.push(JSON.stringify(tempArr));
        }
    }
    validateArr = validateArr.map((item) => {
        return JSON.parse(item);
    });
    for (let row of validateArr) {
        for (let idx in row) {
            if (row[idx].is_selected) {
                validateTxt += "B";
            } else if (row[idx].status) {
                validateTxt += "A";
            } else if (!row[idx].status) {
                validateTxt += "S";
            }
            if (idx < row.length - 1) {
                if (
                    Math.abs(
                        row[Number(idx) + 1].column - row[idx].column
                    ) > 1
                ) {
                    for (
                        let i = 0;
                        i <
                        Math.abs(
                            row[Number(idx) + 1].column -
                                row[idx].column
                        ) -
                            1;
                        i++
                    ) {
                        validateTxt += "O";
                    }
                }
            }
        }
        validateTxt += "@";
    }
    validSeatPosition({
        rowsseats:validateTxt.slice(0, validateTxt.length - 1)
    }).then(res => {
        if(res.success){
            createOrder()
        }else{
            uni.showToast({icon:'none',title:res.msg})
            uni.hideLoading()
        }
    })
}

const createOrder = () => {
    if(!checkLogin())return ;
    const seatNmae = Object.values(checkedMap.value).map(item => {return item.name})
    console.info(seatNmae)
    createMovieOrder({
        mobile:member.value.mobile,
        opiid:Opi.value.opiid,
        seatids:Object.keys(checkedMap.value).join('|'),
        seatnames:seatNmae.join('|'),
        gameTeamId:gameTeamId.value?gameTeamId.value:''
    }).then(res => {
        uni.hideLoading()
        if(res.success){
            checkedMap.value = {}
            showCheckedMap.value = []
            uni.navigateTo({
                url:`/pages/movie/movieOrderConfirm?tradeno=${res.data}&movieId=${Opi.value.movieid}`
            })
        }else{
            uni.showToast({icon:'none',title:res.msg})
        }
    })
}

const sysWidth = ref<any>(0)
let loaded = false
const seatPageInit = () => {
    // Opi.value = uni.getStorageSync('opi')
    getOpiDetail({opiid : opiid.value}).then((opi : any) => {
        if(!opi.success){
            uni.showToast({
                icon:'none',
                title:'场次不存在',
                duration:6000,
                complete:() => {
                uni.reLaunch({
                    url: '/pages/movie/index'
                })
            }})
            return
        }
        Opi.value = opi.data
        Opi.value.opiid = opiid.value

        if(Opi.value && Opi.value.opiid){
            uni.setNavigationBarTitle({
                title: Opi.value.cinemaname
            })
            if(Opi.value.areaPrice){
                const tempArea = Opi.value.areaPrice.split(';')
                tempArea.forEach((item,index) => {
                    const temp = item.split(',')
                    const area = temp[0].split(':')
                    const price = temp[1].split(':')
                    areaMapp.value[area[1]] = {
                        price:price[1],
                        icon:`https://wx.sijiyoufu.com/static/imgs/sites/${index + 1}.svg`,
                        leftIcon:`https://wx.sijiyoufu.com/static/imgs/sites/${index + 1}L.svg`,
                        rightIcon:`https://wx.sijiyoufu.com/static/imgs/sites/${index + 1}R.svg`,
                    }
                    areaPrice.value.push({area:area[1],price:price[1]})
                })
            }else{
                areaMapp.value = {
                    price:Opi.value.price / 100,
                    icon:`https://wx.sijiyoufu.com/static/imgs/sites/1.svg`,
                    leftIcon:`https://wx.sijiyoufu.com/static/imgs/sites/1L.svg`,
                    rightIcon:`https://wx.sijiyoufu.com/static/imgs/sites/1R.svg`,
                }
                areaPrice.value.push({price:Opi.value.price / 100})
            }
            
            getSeats({
                opiid:Opi.value.opiid
            }).then(res => {
                Base.value = res.data.opidetail
                Seats.value = res.data.seatlist
                isLoadding.value = false
                // const temp = {}
                Seats.value.forEach(item => {
                    SeatIndex.value[item.row] = item
                })

                uni.getSystemInfo({
                    success:res=>{
                        sysWidth.value = res.windowWidth
                        const x = Base.value.maxcolumn * Config.value.width + Config.value.width * 2 - sysWidth.value
                        if(x < 0){
                            const count = Base.value.maxcolumn + 4
                            Config.value.width = sysWidth.value / count
                            Config.value.height = sysWidth.value / count
                        }
                        viewX.value = -(x <= 0?0:x)
                    }
                })
                showCheckedMap.value = []
            })
        }else{
            uni.showToast({icon:'none',title:'场次不存在'})
            uni.navigateBack()
        }
    })
    
}
const opiid = ref<any>('')
const gameTeamId = ref<any>('')
onLoad(async (options : any) => {
	const { proxy } = getCurrentInstance();
	await proxy.$onLaunched;
    if(options.scene){
        const usp = decodeURIComponent(options.scene)
        const params = usp.split('=')
        opiid.value = params[1]
       //params[1]二维码扫码参数
    }else opiid.value = options.opiid
    gameTeamId.value = options.gameTeamId
    seatPageInit()
    loaded = true
})

onShow(() => {
    loaded && seatPageInit()
})
</script>
<style lang="scss">
page{
    background:#f5f5f5;
}
.online_body{
    position: fixed;
    width: 100vw;
    height: 65vh;
    left: 20rp;
    top: 0vh;
    z-index: 3;
    overflow: hidden;
    position: relative;
}
.cell_base_box{
    width:52px;
    height:52px;
    border-radius: 6rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    position:absolute;
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
}
.online_body_number{
    position:absolute;
    left:0;
    top:0px;
    z-index: 9;
    background:rgba(0,0,0,.72);
    border-radius:52px;
    .index_number{
        text-align:center;
        color:#fff;
    }
}
.seatNotice{
    display:flex;
    align-items: center;
    white-space: nowrap;
    overflow-x: scroll;
    font-size:24upx;
    padding:26upx;
    .seatItem{
        flex-basis: 160upx;
        flex-shrink: 0;
        white-space: nowrap;
        display:flex;
        align-items: center;
        image{
            margin-right:12upx;
        }
    }
}
.screen_body{
    width:52%;
    height:15upx;
    border-radius: 50%;
    background:#ccc;
    margin:0 auto;
    font-size: 22rpx;
    text-align: center;
    line-height: 3;
}
.opi_info{
    width:92%;
    margin:32upx auto;
    padding:32upx;
    border-radius:9px;
    background:#fff;
    color:#666;
    font-size: 26upx;
    box-sizing: border-box;
    .title{
        font-size:36upx;
        font-weight:600;
        color:#000;
    }
    .selector{
        display:flex;
        align-items: center;
        white-space: nowrap;
        overflow-x: scroll;
        font-size:24upx;
        padding:26upx 0 0;
        .selector_item{
            flex-basis: 160upx;
            flex-shrink: 0;
            white-space: nowrap;
            display:flex;
            align-items: center;
            border: 1px dotted #ccc;
            padding: 12rpx 22rpx;
            border-radius: 5px;
            color:red;
            margin-right:22upx;
            text{
                font-weight: 600;color:#000;margin-left:12upx;
                &.notice{font-weight: 400;color:999;margin:0;}
            }
            .image{
                margin-left:12upx;
                color:#666
            }
        }
    }
}
.btn {
    width: 92%;
    height: 88upx;
    line-height: 88upx;
    font-size: 36upx;
    border-radius: 50upx;
    font-weight: 600;
    color:#fff;
    margin:32rpx auto;
    text-align:center;
}
</style>